package com.itheima.easy.handler.aliyun;

import com.alibaba.fastjson.JSONObject;
import com.alipay.easysdk.kernel.Config;
import com.alipay.easysdk.kernel.util.ResponseChecker;
import com.alipay.easysdk.payment.page.models.AlipayTradePagePayResponse;
import com.itheima.easy.client.alipay.Factory;
import com.itheima.easy.constant.SuperConstant;
import com.itheima.easy.constant.TradingConstant;
import com.itheima.easy.enums.TradingEnum;
import com.itheima.easy.exception.ProjectException;
import com.itheima.easy.handler.PagePayHandler;
import com.itheima.easy.pojo.Trading;
import com.itheima.easy.utils.BeanConv;
import com.itheima.easy.utils.EmptyUtil;
import com.itheima.easy.utils.ExceptionsUtil;
import com.itheima.easy.vo.TradingVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @ClassName AliPagePayHandler.java
 * @Description PC网页支付处理实现
 */
@Slf4j
@Component
public class AliPagePayHandler  extends AliCommonPayHandler implements PagePayHandler {


    @Override
    public TradingVo pageTrading(TradingVo tradingVo) {
        //1、交易前置处理：检测交易单参数
        Boolean flag = beforePayHandler.checkCreateTrading(tradingVo);
        if (!flag){
            throw new ProjectException(TradingEnum.TRAD_PAY_FAIL);
        }
        //2、交易前置处理：幂等性处理
        beforePayHandler.idempotentCreateTrading(tradingVo);
        //3、获得支付宝配置文件
        Config config = aliPayConfig.config(tradingVo.getEnterpriseId());
        //4、配置如果为空，抛出异常
        if (EmptyUtil.isNullOrEmpty(config)){
            throw new ProjectException(TradingEnum.CONFIG_ERROR);
        }
        //5、使用配置
        Factory factory = new Factory();
        factory.setOptions(config);
        try {
            //6、调用支付宝API
            AlipayTradePagePayResponse pagePayResponse = factory.Page().pay(tradingVo.getMemo(),
                String.valueOf(tradingVo.getTradingOrderNo()),
                String.valueOf(tradingVo.getTradingAmount()),
                tradingVo.getReturnUrl());
            //7、受理结果【只表示请求是否成功，而不是支付是否成功】
            boolean isSuccess = ResponseChecker.success(pagePayResponse);
            if (isSuccess&&!EmptyUtil.isNullOrEmpty(pagePayResponse.getBody())){
                tradingVo.setIsRefund(SuperConstant.NO);
                tradingVo.setPlaceOrderCode(TradingConstant.ALI_SUCCESS_CODE);
                tradingVo.setPlaceOrderMsg(TradingConstant.ALI_SUCCESS_MSG);
                tradingVo.setPlaceOrderJson(pagePayResponse.getBody());
                tradingVo.setTradingState(TradingConstant.TRADE_WAIT_BUYER_PAY);
                Trading trading = BeanConv.toBean(tradingVo, Trading.class);
                tradingService.save(trading);
            }else {
                log.error("网关：支付宝网页支付统一下单创建：{},结果：{}", tradingVo.getTradingOrderNo(),
                    JSONObject.toJSONString(pagePayResponse));
                throw new RuntimeException("网关：支付宝网页支付统一下单创建失败！");
            }
        } catch (Exception e) {
            log.error("支付宝网页支付统一下单创建失败：{}", ExceptionsUtil.getStackTraceAsString(e));
            throw new RuntimeException("支付宝网页支付统一下单创建失败!");
        }
        return tradingVo;
    }
}
